import json
from py2neo import *
from django.shortcuts import render

# 连接数据库
graph = Graph('http://localhost:7474', user='neo4j', password='yhf20001116', name='neo4j')
# def search_all():
#     data = []  # 定义data数组，存放节点信息
#     links = []  # 定义关系数组，存放节点间的关系
#     for n in graph.nodes:
#         nodesStr = json.dumps(graph.nodes[n], ensure_ascii=False) # 将节点信息转化为json格式，否则中文会不显示
#         data_json = json.loads(nodesStr)
#
#         node_name = data_json['name']   # 取出节点的name
#         dict = {
#                 'name': node_name,
#                 'symbolSize': 50,
#                 'categories': 1
#             }
#         data.append(dict)  # 将单个节点信息存放在data数组中
#     rps = graph.relationships  # 查询所有关系，并将所有的关系信息存放在links数组中
#     for r in rps:
#         source = str(rps[r].start_node['name'])
#         target = str(rps[r].end_node['name'])
#         name = str(type(rps[r]).__name__)         # 取出开始节点的结束节点之间的关系
#         dict = {
#             'source': source,
#             'target': target,
#             'type': name
#         }
#         links.append(dict)
#     for item in data:
#         print(item)
#     # # 输出所有关系信息
#     # for item in links:
#     #     print(item)
#     # 将所有的节点信息和关系信息存放在一个字典中
#     neo4j_data = {
#         'data': data,
#         'links': links
#     }
#     #将字典转化json格式
#     neo4j_data = json.dumps(neo4j_data, ensure_ascii=False)
#     return neo4j_data
def visualize_data():
    query = "MATCH (n) RETURN n"
    results = graph.run(query).data()
    rps = graph.relationships
    data = []
    links = []
    for result in results:
        print(result)
        node = {"id":str(result['n'].identity),
                "name": result['n']['name'],
                "desc":result['n']['desc'],
                'cure_department':result['n']['cure_department'],
                'symbolSize': 50,
                'category': str(result['n'].labels)}
        data.append(node)
        print(node)
    for r in rps:
        source_id = rps[r].start_node.identity
        target_id = rps[r].end_node.identity
        name = str(type(rps[r]).__name__)
        link = {"source": str(source_id), "target": str(target_id), "type": name}
        links.append(link)
    return json.dumps({"data": data, "links": links},ensure_ascii=False)

def search_one(value):
    # 定义data数组存储节点信息
    data = []
    # 定义links数组存储关系信息
    links = []
    # 查询节点是否存在
    node = graph.run('MATCH(n:person{name:"' + value + '"}) return n').data()
    # 如果节点存在len(node)的值为1不存在的话len(node)的值为0
    if len(node):
        # 如果该节点存在将该节点存入data数组中
        # 构造字典存放节点信息
        dict = {
            'name': value,
            'symbolSize': 50,
            'category': '对象'
        }
        data.append(dict)
        # 查询与该节点有关的节点，无向，步长为1，并返回这些节点
        nodes = graph.run('MATCH(n:person{name:"' + value + '"})<-->(m:person) return m LIMIT 5').data()
        # 查询该节点所涉及的所有relationship，无向，步长为1，并返回这些relationship
        reps = graph.run('MATCH(n:person{name:"' + value + '"})<-[rel]->(m:person) return rel LIMIT 5').data()
        # 处理节点信息
        for n in nodes:
            # 将节点信息的格式转化为json
            node = json.dumps(n, ensure_ascii=False)
            node = json.loads(node)
            # 取出节点信息中person的name
            name = str(node['m']['name'])
            # 构造字典存放单个节点信息
            dict = {
                'name': name,
                'symbolSize': 50,
                'category': '对象'
            }
            # 将单个节点信息存储进data数组中
            data.append(dict)
        # 处理relationship
        for r in reps:
            source = str(r['rel'].start_node['name'])
            target = str(r['rel'].end_node['name'])
            name = str(type(r['rel']).__name__)
            dict = {
                'source': source,
                'target': target,
                'name': name
            }
            links.append(dict)
        # 构造字典存储data和links
        search_neo4j_data = {
            'data': data,
            'links': links
        }
        # 将dict转化为json格式
        search_neo4j_data = json.dumps(search_neo4j_data)
        return search_neo4j_data
    else:
        # print("查无此节点")
        return 0


def index(request):
    # ctx = {}
    neo4j_data = visualize_data()
    return render(request, 'index.html', {'neo4j_data': neo4j_data})
